(function ($, _) {
    "use strict";
    var e = {},
        $loading = $("#loading-bar"),
        $dataHolder = $("#result-data-table"),
        cellTemplate = $("#result-cell").html(),
        loadable = true,
        $collection = $("#collection"),
        $maxLine = $("#max-line-inner"),
        maxLineTemplate = $("#max-line-inner-template").html(),
        collections,
        goToMaxLineTrace = null,
        currentColumnHover,
        $dataTable = $("table", "#data-table"),
        initializeLoadCompleted = false,
        $lastTrF,
        $lastTrL,
        loading = false,
        $doc = $(document);



    $doc.ajaxSend(function () {
        $loading.clearQueue().show();
    }).ajaxComplete(function () {
            $loading.hide();
        });

    var updateWin = function () {
        if (!initializeLoadCompleted || $collection.val() == "null") return;
        var selNumbers = collections[$collection.val()];
        console.log($("td", $dataHolder).length);
        $("td", $dataHolder).removeClass("win").each(function () {
            if (_(selNumbers).contains($(this).data('number'))) {
                $(this).addClass("win");
            }
        });
    };

    // Nhận kết quả dãy dài nhất khi thay đổi bộ chọn
    var getMaxLine = function () {
        if (!initializeLoadCompleted || $collection.val() == "null") return;
        var collection = $collection.val();
        $maxLine.animate({opacity: 0}, 200);
        $.getJSON(e.apiUrl + "maxline/" + collection, function (json) {
            /*
             Object {f: Object, l: Object}
             f: Object
             count: 2
             start: 3848
             __proto__: Object
             l: Object
             count: 2
             start: 1127
             __proto__: Object
             __proto__: Object
             */
            $maxLine.html(_.template(maxLineTemplate, {
                fMax: json.f.count,
                fCell: json.f.start,
                lMax: json.l.count,
                lCell: json.l.start
            })).animate({ opacity: 1}, 500);
        });
    };

    $dataTable.on("mouseenter", "th, td", function () {
        currentColumnHover = $(this).data('column-id');
        $(".column-" + currentColumnHover, $dataTable).addClass("hover");
    }).on("mouseleave", "th, td", function () {
            $(".hover", $dataTable).removeClass("hover");
        });

    // Change selected
    $collection.on("change", function () {
        updateWin();
        getMaxLine();
    });

    $maxLine.on("click", "span.label", function () {
        var cellId = $(this).data("cell");
        console.log("go cell " + cellId);
        goToMaxLineTrace = cellId;
        goMaxLine();
    });

    var goMaxLine = function () {
        if (goToMaxLineTrace != null) {
            var $cell = $("#" + goToMaxLineTrace);
            if ($cell.length > 0) {
                $("body, html").scrollTop($cell.position().top - 20);
                goToMaxLineTrace = null;

                $(".max-line-start").removeClass("max-line-start");
                var $tmp = $cell;
                while (true) {
                    if (!$tmp.is(".win")) break;

                    $tmp.addClass("max-line-start");

                    if ($tmp.next().length > 0) {
                        $tmp = $tmp.next();
                    } else {
                        if ($tmp.parent().next().length == 0 || $tmp.parent().next().next().length == 0) break;
                        $tmp = $tmp.parent().next().next().children(":first");
                    }
                }
            } else {
                e.load(false);
            }
        }
    };

    // last time loading
    e.lastTime = 0;
    e.apiUrl = "api/";
    e.loadUrl = e.apiUrl + "result/";

    // load collection
    e.loadCollections = function () {
        $.getJSON(e.apiUrl + "collection/", function (json) {
            $collection.empty().html('<option value="null">Bộ chọn</option>');
            collections = {};

            // Append collection to select box
            _(json).each(function (curCln) {
                collections[curCln.id] = curCln.numbers;
                $("<option/>").attr("value", curCln.id)
                    .text(curCln.name)
                    .appendTo($collection);
            });

            $collection.val("null");
            initializeLoadCompleted = true;
        });
    };

    // Load more data
    e.loadMoreData = function (loadMoreCallback) {
        if (loadable) {
            loading = true;
            $.getJSON(e.loadUrl + e.lastTime, function (json) {
                // DEBUG
                console.log("Load data: " + json.lastTime + " -> " + json.nextTime);

                if (json.data.length > 0) {
                    var lastRecord = _(json.data).last();
                    e.lastTime = lastRecord.time;
                }

                loadable = json.data.length > 0;
                loadMoreCallback(json.data);
                loading = false;
                $loading.hide();
            });
        }
    };

    e.load = function (firstLoad) {
        e.loadMoreData(function (data) {

            if (data.length == 0) {
                return;
            }
            var firstRecord = _(data).first(),
                lastRecord = _(data).last(),
                counter = 0,
                curRowHtmlF = "",
                curRowHtmlL = "";

            if (firstLoad) {
                for (var i = 6; i > firstRecord.weekday; i--) {
                    var curCellHtml = _.template(cellTemplate, {
                        column: i,
                        win: false,
                        number: null,
                        date: null,
                        holder: false,
                        id: _.uniqueId("c")
                    });

                    curRowHtmlF += curCellHtml;
                    curRowHtmlL += curCellHtml;
                }
            } else {
                $("td.holder", $lastTrF).each(function () {
                    var self = $(this);
                    var o = data[counter];
                    self.data("number", o.fn)
                        .data("date", o.time)
                        .text(o.fn);

                    $lastTrL.find("td.column-" + o.weekday)
                        .data("number", o.ln)
                        .data("date", o.time)
                        .text(o.ln);

                    counter++;
                });
            }

            var appendHtml = function () {
                $dataHolder.append(
                    $lastTrF = $("<tr class='first'/>").html(curRowHtmlF),
                    $lastTrL = $("<tr class='last'/>").html(curRowHtmlL)
                );
                curRowHtmlF = "";
                curRowHtmlL ="";
            };
            while (true) {

                var curResult = data[counter];
                curRowHtmlF += _.template(cellTemplate, {
                    column: curResult.weekday,
                    win: false,
                    number: curResult.fn,
                    date: curResult.time,
                    holder: false,
                    id: "f-" + curResult.id
                });

                curRowHtmlL += _.template(cellTemplate, {
                    column: curResult.weekday,
                    win: false,
                    number: curResult.ln,
                    date: curResult.time,
                    holder: false,
                    id: "l-" + curResult.id
                });

                if (curResult.weekday == 0) {
                    appendHtml();
                }

                if (++counter == data.length) {

                    for (i = lastRecord.weekday - 1; i >= 0; i--) {
                        curCellHtml = _.template(cellTemplate, {
                            column: i,
                            win: false,
                            number: null,
                            date: null,
                            holder: true,
                            id: _.uniqueId("c")
                        });

                        curRowHtmlF += curCellHtml;
                        curRowHtmlL += curCellHtml;
                    }

                    appendHtml();
                    break;
                }
            }

            updateWin();

            goMaxLine();
        });
    };





    e.start = function () {
        e.loadCollections();
        e.load(true);

        $doc.scroll(function () {
            if ($doc.scrollTop() >=  $doc.height() - $(window).height() && !loading) {
                e.load(false);
            }

            if ($doc.scrollTop() >= 200) {
                $("#go-top").fadeIn(300);
            } else {
                $("#go-top").fadeOut(200);
            }
        });
    };

    $("#go-top").click(function () {
        $("body,html").animate({
            scrollTop: 0
        }, 800);
    });

    e.start();
}(window.jQuery, window._));